package cn.iocoder.mall.promotion.application.controller.users;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.utils.common.api.vo.Result;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.util.DateUtils;
import cn.iocoder.common.utils.common.util.ObjectUtils;
import cn.iocoder.mall.promotion.api.CouponService;
import cn.iocoder.mall.promotion.api.bo.CouponCardAvailableBO;
import cn.iocoder.mall.promotion.api.bo.CouponCardBO;
import cn.iocoder.mall.promotion.api.bo.CouponCardPageBO;
import cn.iocoder.mall.promotion.api.bo.CouponTemplateBO;
import cn.iocoder.mall.promotion.api.constant.CouponTemplateDateTypeEnum;
import cn.iocoder.mall.promotion.api.constant.RangeTypeEnum;
import cn.iocoder.mall.promotion.api.dto.CouponCardPageDTO;
import cn.iocoder.mall.promotion.api.dto.CouponCardSpuDTO;
import cn.iocoder.mall.promotion.application.convert.CouponCardConvert;
import cn.iocoder.mall.promotion.application.convert.CouponTemplateConvert;
import cn.iocoder.mall.promotion.application.vo.coupon.PersonalCouponCardVO;
import cn.iocoder.mall.promotion.application.vo.users.UsersCouponCardPageVO;
import cn.iocoder.mall.promotion.application.vo.users.UsersCouponCardVO;
import cn.iocoder.mall.promotion.application.vo.users.UsersCouponTemplateVO;
import cn.iocoder.mall.user.api.AppMessageService;
import cn.iocoder.mall.user.api.constant.AppMessageTypeEnum;
import cn.iocoder.mall.user.api.dto.AppMessageDTO;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.common.framework.vo.CommonResult.success;

@RestController
@RequestMapping("/users/coupon")
@Api("优惠劵（码）模块")
public class UsersCouponController {

    @Reference(validation = "true", version = "${dubbo.provider.CouponService.version}")
    private CouponService couponService;

    @Reference(validation = "true", version = "${dubbo.consumer.AppMessageService.version}")
    private AppMessageService appMessageService;


    // ========== 优惠劵（码）模板 ==========

    @GetMapping("/template/get")
    @ApiOperation(value = "优惠劵（码）模板信息")
    @ApiImplicitParam(name = "id", value = "优惠劵（码）模板编号", required = true, example = "10")
    public CommonResult<UsersCouponTemplateVO> templateGet(@RequestParam("id") Integer id) {
        CouponTemplateBO template = couponService.getCouponTemplate(id);
        return success(CouponTemplateConvert.USERS.convert2(template));
    }

    // ========== 优惠劵 ==========

    @GetMapping("/card/page")
    @ApiOperation(value = "优惠劵分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态", example = "参考 CouponCardStatusEnum 枚举"),
            @ApiImplicitParam(name = "pageNo", value = "页码，从 1 开始", example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, example = "10"),
    })
    public CommonResult<UsersCouponCardPageVO> cardPage(@RequestParam(value = "status", required = false) Integer status,
                                                        @RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        CouponCardPageBO result = couponService.getCouponCardPage(new CouponCardPageDTO()
                .setStatus(status).setUserId(JwtUtil.getUserIdByToken())
                .setPageNo(pageNo).setPageSize(pageSize));
        return success(CouponCardConvert.INSTANCE.convert2(result));
    }

    @GetMapping("/card/add")
    @ApiOperation(value = "领取优惠劵")
    @ApiImplicitParam(name = "templateId", value = "优惠劵（码）模板编号", required = true, example = "10")
    public CommonResult<UsersCouponCardVO> cardAdd(@RequestParam("templateId") Integer templateId) {
        CouponCardBO result = couponService.addCouponCard(JwtUtil.getUserIdByToken(), templateId);
        //-----------添加消息推送-------------
        AppMessageDTO app = new AppMessageDTO();
        app.setReceiver(String.valueOf(result.getUserId()));
        app.setType(AppMessageTypeEnum.ACTIVITY_NOTICE.getValue());
        app.setTitle("领取优惠券");
        app.setCreateTime(DateUtils.getDate());
        CouponTemplateBO couponTemplate = couponService.getCouponTemplate(templateId);
        app.setContent(JSONObject.toJSONString(couponTemplate));
        app.setEntitiesId(result.getShopId());
        appMessageService.sendAppMessageToUser(app);

        return success(CouponCardConvert.INSTANCE.convert(result));
    }

    @GetMapping("/template/listByShopId")
    public Result getCardTemplateListByShopId(@RequestParam String shopId) {

        return Result.ok(couponService.getCouponTemplateListByShopId(shopId));

    }

    @GetMapping("/template/listBySpuId")
    public Result getCardTemplateListBySpuId(@RequestParam String shopId, @RequestParam String spuId) {

        List<CouponTemplateBO> list = couponService.getCouponTemplateListByShopId(shopId);
        list = list.stream().filter(o -> {
            if (RangeTypeEnum.ALL.getValue().equals(o.getRangeType())) {
                return true;
            }
            if (!RangeTypeEnum.ALL.getValue().equals(o.getRangeType()) &&o.getRangeValues()==null) {
                return false;
            }
            if (RangeTypeEnum.PRODUCT_INCLUDE_PART.getValue().equals(o.getRangeType()) &&!o.getRangeValues().contains(",")&&o.getRangeValues().contains(spuId)){
                return true;
            }
            if (RangeTypeEnum.PRODUCT_INCLUDE_PART.getValue().equals(o.getRangeType()) &&o.getRangeValues().contains(spuId)){
                return true;
            }
            if (CouponTemplateDateTypeEnum.FIXED_DATE.getValue().equals(o.getDateType()) &&o.getValidEndTime().getTime()>System.currentTimeMillis()
            &&o.getValidStartTime().getTime()<System.currentTimeMillis()
            ){
                return true;
            }
            if (CouponTemplateDateTypeEnum.FIXED_DATE.getValue().equals(o.getDateType()) &&
                    DateUtil.between(o.getCreateTime(),new Date(), DateUnit.DAY)>=o.getFixedStartTerm()
                    &&DateUtil.between(o.getCreateTime(),new Date(), DateUnit.DAY)<=o.getFixedEndTerm()
            ){
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        return Result.ok(list);

    }
    @PostMapping("/getPersonalCouponList")
    public Result getPersonalCouponList (@RequestBody PersonalCouponCardVO vo){
        List<CouponCardSpuDTO> list=ObjectUtils.copyList(vo.getSpuList(),CouponCardSpuDTO.class);
        List<CouponCardAvailableBO> detailList=couponService.getCouponCardList(JwtUtil.getUserIdByToken(),list);
        return Result.ok(detailList);
    }


    // ========== 优惠码 ==========


}
